<template>
  <div class="bills">
    <div class="head-con">
      <div class="searchDiv">
        <label class="label_input">
          <span style="color: red">*</span>客户:</label
        > 
        
        <el-input v-model="customerForm.customerName" placeholder="点击选择客户"
            @click="openCustomerDialog" readonly style="width: 200px;" />
        <CustomerDialog v-model="customerDialogVisible" @confirm="handleSelectCustomer" />
        <!-- 源单对话框 -->
        <SourceDocDialog
          ref="sourceDocDialog"
          :source-doc-list="availableSourceDocs"
          @confirm="handleSourceDocConfirm"
          :disabled="!selectCustomer" 
        />

        
      </div>

      <div class="searchDiv">
        <label class="label_input">总欠款:</label>
        <el-input
          v-model="TotalDebt"
          style="width: 100px"
          disabled
          placeholder="0.00"
        />
      </div>

      <div class="searchDiv">
        <label class="label_input">负责人:</label>
        <el-select
          v-model="responsible"
          style="width: 130px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in responsibleOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="searchDiv">
        <label class="label_input">单据日期:</label>
        <el-date-picker v-model="date" type="date" />
      </div>

      <div class="searchDiv">
        <label class="label_input">单据编号:</label>
        <span v-if="!editingBillNo" @click="editBillNo" class="bill-no">{{
          billNo
        }}</span>
        <el-input
          v-else
          v-model="tempBillNo"
          ref="billNoInput"
          style="width: 150px"
          @blur="saveBillNo"
          @keyup.enter="saveBillNo"
        />
      </div>
      <hr />
    </div>

    <div class="settlement-table">
      <el-table
        :data="settlementItems"
        style="width: 100%"
        border
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :cell-style="tableCellStyle"
      >
        <el-table-column type="index" label="序号" width="50" align="center">
          <template #default="{ $index, row }">
            <span v-if="!row.isTotalRow">{{ $index + 1 }}</span>
            <span v-else></span>
          </template>
        </el-table-column>

        <!-- 结算账户列代码 -->
        <el-table-column prop="account" label="*结算账户" min-width="150">
          <template #default="{ row }">
            <el-select
              v-model="row.account"
              placeholder="请先选择结算账户"
              style="width: 100%"
              v-if="!row.isTotalRow"
            >
              <el-option
                v-for="item in accountList"
                :key="item.value"  
                :label="item.label"  
                :value="item.value"  
              />
            </el-select>
            <span v-else> 合计: </span>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="*付款金额" min-width="120">
          <template #default="{ row }">
            <el-input
              v-model.number="row.amount"
              type="number"
              placeholder="0.00"
              step="0.01"
              style="width: 100%"
              @change="calculateTotal"
              v-if="!row.isTotalRow"
            />
            <span v-else>{{ totalAmount }} </span>
          </template>
        </el-table-column>

        <el-table-column prop="method" label="结算方式" min-width="120">
          <template #default="{ row }">
            <el-select
              v-model="row.method"
              placeholder="请选择结算方式"
              style="width: 100%"
              v-if="!row.isTotalRow"
            >
              <el-option label="银行转账" value="transfer" />
              <el-option label="支票" value="check" />
              <el-option label="汇票" value="draft" />
              <el-option label="现金" value="cash" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column prop="settlementNo" label="结算号" min-width="130">
          <template #default="{ row }">
            <el-input
              v-model="row.settlementNo"
              placeholder="结算号"
              style="width: 100%"
              v-if="!row.isTotalRow"
            />
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" min-width="150">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder="备注信息"
              style="width: 100%"
              v-if="!row.isTotalRow"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="80" align="center">
          <template #default="{ $index }">
            <el-button
              type="text"
              size="small"
              :icon="CirclePlus"
              @click="addSettlementRow($index)"
              v-if="isTotalRow($index)"
            />
            <el-button
              type="text"
              size="small"
              :icon="Delete"
              @click="removeSettlementRow($index)"
              v-if="isDeleteRow($index)"
              style="color: #f56c6c"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="middle-div">
      <el-button round @click="sourceDocDialog.open()" :disabled="!selectCustomer">选择源单</el-button>
      <el-button round @click="autoWriteOff">自动核销</el-button>
    </div>

    <div class="settlement-table">
      <el-table
        :data="SourceDocuments.length>0?SourceDocuments:placeholderRows"
        style="width: 100%"
        border
        :header-cell-style="{ 'background-color': '#f5f7fa' }"
        :cell-style="tableCellStyle"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="docNo" label="源单编号" min-width="130">
          <template #default="{ row }">
            <span v-if="row.docNo" class="link-text">{{ row.docNo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="businessType" label="业务类别" min-width="100" />
        <el-table-column prop="docDate" label="单据日期" min-width="110" />
        <el-table-column label="单据金额" min-width="100">
          <template #default="{ row }">
            <span v-if="row.docNo">
              {{ Number(row.slipPrice).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="writtenOffAmount"
          label="已核销金额"
          min-width="110"
        />
        <el-table-column
          prop="unwrittenOffAmount"
          label="未核销金额"
          min-width="110"
        />
        <el-table-column
  prop="currentWriteOffAmount"
  label="*本次核销金额"
  min-width="130"
>
  <template #default="{ row }">
    <el-input
      v-model.number="row.currentWriteOffAmount"
      type="number"
      step="0.01"
      style="width: 100px"
      :max="row.businessType === '普通销售' ? row.unwrittenOffAmount : null"
      :min="row.businessType === '销售退货' ? row.unwrittenOffAmount : 0.01"
      @keydown="preventExceedMax($event, row.unwrittenOffAmount, row)"
      @change="validateWriteOffAmount(row)"
      @blur="validateWriteOffAmount(row)"
      v-if="row.docNo"
    />
  </template>
</el-table-column>
        <el-table-column prop="remark" label="单据备注" min-width="150" />
        <el-table-column label="操作" width="80" align="center">
          <template #default="{ $index }">
            <el-button
              type="text"
              size="small"
              :icon="CirclePlus"
              @click="addSourceDocRow"
              v-if="isSourceDocLastRow($index)"
            />
            <el-button
              type="text"
              size="small"
              :icon="Delete"
              @click="removeSourceDocRow($index)"
              v-if="canDeleteSourceDocRow($index)"
              style="color: #f56c6c"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="note">
      <el-input v-model="note" :rows="2" type="textarea" placeholder="备注" />
    </div>

    <div
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;
      "
    >
      <div>
        <span>本次预收款:</span>
        <el-input-number
          v-model="remainAmount"
          :precision="2"
          :min="0"
          :controls="false"
          :disabled="true"
          style="margin-left: 10px; width: 150px"
        ></el-input-number>
      </div>

      <div style="position: fixed; top: 150px; right: 50px; z-index: 9999; display: flex; gap: 1px;">
        <el-button type="primary" @click="addNew" style="font-size:12px">新增</el-button>
        <el-button type="primary" @click="save" style="font-size:12px">保存</el-button>
        <el-button type="primary" @click="putit" style="font-size:12px">提交</el-button>
        <el-button type="primary" @click="handleAudit" style="font-size:12px">审核</el-button>
        <el-button type="primary" @click="back" style="font-size:12px">驳回</el-button>
      </div>

      <div class="status-indicator" v-if="showStatus">
        <img :src="statusImageUrl" :alt="statusAltText" class="status-image" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import {  CirclePlus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import SourceDocDialog from "@/util/SourceDocDialog.vue";
import CustomerDialog from "@/util/CustomerDialog.vue";
import dayjs from "dayjs";
import axios from "axios";
import { useRoute,useRouter } from 'vue-router';
// import { ca } from "element-plus/es/locale";
const router = useRouter();
const route = useRoute();
//查询客户
// const Customer = ref("");
//显示欠款
const TotalDebt = ref("");
//负责人选择
const responsible = ref("");
//单据日期选择
const date = ref(dayjs().format('YYYY-MM-DD'))
const receipt_id = ref(null);
//空数据
const placeholderRows = ref(Array(5).fill({ isPlaceholder: true })); // 5行空数据
// 对话框引用
// const customerDialog = ref(null);
const sourceDocDialog = ref(null);
const customerForm = reactive({
  customerCode:'',
  customerAddress:'',
  customerName: '',
  customerType:''
});
// 客户对话框启用
const customerDialogVisible = ref(false)
// 打开客户选择弹窗
const openCustomerDialog = () => {
    customerDialogVisible.value = true
}

// 客户选择
const handleSelectCustomer = (customers) => {
  console.log('customer',customers)
  if (customers && customers.length > 0) {
    const customer = customers[0];
    customerForm.customerCode = customer.code;
    customerForm.customerAddress = customer.primaryContactAddress || '';
    customerForm.customerName = customer.name;
    customerForm.customerType = customer.typeName;
    TotalDebt.value = (customer.initialReceivable - customer.initialAdvance).toFixed(2);
    selectCustomer.value = customer;
    getAvailableSourceDocs();
  }
  customerDialogVisible.value = false;
};
// 处理源单选择确认
const handleSourceDocConfirm = (docs) => {
  const newDocs = docs.map(doc => ({
    ...doc,
    currentWriteOffAmount: 0,
  }));

  if (isEditMode.value && SourceDocuments.value.length > 0) {
    const existingDocNos = new Set(SourceDocuments.value.map(d => d.docNo));
    const uniqueNewDocs = newDocs.filter(doc => !existingDocNos.has(doc.docNo));

    SourceDocuments.value = [...SourceDocuments.value, ...uniqueNewDocs];
  } else {
    // 首次选择或新增模式：直接覆盖
    SourceDocuments.value = newDocs;
  }

  calculateTotal();
};

//存储选中的客户信息
const selectCustomer=ref([]);

// 客户列表数据
const customerList = ref([]);
let responsibleOptions = ref([
  {
    id: "1",
    label: "老板",
  },
  {
    id: "2",
    label: "组长-老陈",
  },
  {
    id: "3",
    label: "采购组员-小鹏",
  },
  {
    id: "4",
    label: "采购组员-小亮",
  },
]);

// 单据编号相关
const billNo = ref("");
const tempBillNo = ref("");
const editingBillNo = ref(false);
const billNoInput = ref(null);
// 页面加载时生成默认编号
onMounted(async () => {
  await Promise.all([
    getAccountList(),
    getCustomerList()
  ]);

  // 再处理单据逻辑
  if (isEditMode.value) {
    await loadReceiptData(route.query.code);
  } else {
    generateDefaultBillNo();
  }
});
const getCustomerList = async () => {
  try {
    const response = await axios.get("/finance/customerPage",{params:{pageNum:1,pageSize:100}});
    if (response.data.code === 5200) {
      customerList.value = response.data.customerList;
      console.log('customerList',customerList.value)
    } else {
      ElMessage.error("获取客户失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取客户出错：", error);
    ElMessage.error("网络错误，无法获取客户数据");
  }
};

// **********
const isEditMode = computed(() => !!route.query.code);
const loadReceiptData = async (receiptCode) => {
  console.log('code',receiptCode)
  try {
    const response = await axios.get('/finance/getReceiptByCode', {
      params: { receiptCode:receiptCode }
    });
    // console.log('response',response.data)
    
    const data = response.data.receipt;
    console.log('data',data)
    // 基础信息
    receipt_id.value= data.receipt_id;
    billNo.value = data.receipt_code;
    tempBillNo.value = data.receipt_code;
    date.value = data.receipt_date;
    note.value = data.memo || '';
    const selectedCustomerForEdit = ref(null);
    // 客户信息
    selectedCustomerForEdit.value = customerList.value.find(c => String(c.id) === String(data.customer_id)) || null;
    customerForm.customerName = selectedCustomerForEdit.value?.name || '';
    TotalDebt.value = (
      (selectedCustomerForEdit.value?.initialReceivable || 0) - 
      (selectedCustomerForEdit.value?.initialAdvance || 0)
    ).toFixed(2);
    selectCustomer.value = selectedCustomerForEdit.value;
    // if(selectCustomer.value){
       getAvailableSourceDocs();
      // 结算账户明细
      settlementItems.value = [];
      if (data.receiptAccountList && data.receiptAccountList.length > 0) {
        for (const acc of data.receiptAccountList) {
          settlementItems.value.push({
            account: acc.accountCode,
            amount: Number(acc.amount) || 0,
            method: acc.receipt_method || '', 
            settlementNo: acc.settlement_no || '',
            remark: acc.remark || ''
          });
        }
      } else {
        // 兜底：至少一行
        settlementItems.value.push({
          account: data.account_id || '',
          amount: Number(data.amount) || 0,
          method: data.receipt_method || '',
          settlementNo: '',
          remark: ''
        });
      }
    // } else {
    //   ElMessage.warning("未找到对应客户信息");
    // }
    console.log('settle',settlementItems)

    // 添加合计行
    settlementItems.value.push({
      account: "合计:",
      amount: totalAmount.value,
      method: "",
      settlementNo: "",
      remark: "",
      isTotalRow: true,
    });

    calculateTotal(); // 触发合计计算

    // 源单明细（SourceDocuments）
    SourceDocuments.value = [];
    if (data.salesSlipList && data.salesSlipList.length > 0) {
      SourceDocuments.value = data.salesSlipList.map(doc => ({
        docId: doc.id,
        docNo: doc.isReturn === 1 ? doc.returnCode : doc.code,
        businessType: doc.isReturn===1?'销售退货':'普通销售',
        docDate: doc.date,
        docAmount: doc.slipPrice || 0,
        sa: doc.slipPrice ||0,
        slipPrice: doc.isReturn===1?-(doc.slipPrice).toFixed(2):(doc.slipPrice).toFixed(2),
        thisPayment :doc.thisPayment || 0,
        // 确保从后端获取最新的已核销金额
        writtenOffAmount: doc.isReturn===1? -(doc.written_off_amount).toFixed(2) :(doc.written_off_amount).toFixed(2) || 0,
        currentWriteOffAmount: doc.isReturn===1? -(doc.current_written_off_amount).toFixed(2) :(doc.current_written_off_amount).toFixed(2) || 0,
        // 计算未核销金额
        get unwrittenOffAmount() {
          const docAmount = Number(this.slipPrice) || 0;
          const writtenOff = Number(this.writtenOffAmount) || 0;
          // const writtenOffAmount = Number(this.currentWriteOffAmount) || 0;
          return (docAmount - writtenOff).toFixed(2);
        },
        remark: doc.remarks || "",
        customer_code: doc.customer_code
      }));
    }

    // 状态图片（如果已审核）
    if (data.status === 2) {
      showStatus.value = true;
      statusImageUrl.value = imagePaths.passed;
      statusAltText.value = "审核通过";
    }

  } catch (error) {
    console.error('加载收款单失败:', error);
    ElMessage.error('加载收款单失败，请重试');
  } 
};

// *************



// 生成默认单据编号 
const generateDefaultBillNo = async () => {
  try {
    // 从后端获取最新序号
    const response = await axios.get("/finance/getNextReceiptNo");
    console.log('最新序号',response.data)
    if (response.data.code === 5200) {
      billNo.value = response.data.billNo;
      tempBillNo.value = billNo.value;
    } else {
      // 后端获取失败时使用本地默认值
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      billNo.value = `RECEIPT${year}${month}${day}001`;
      tempBillNo.value = billNo.value;
    }
  } catch (error) {
    console.error("获取单据编号失败：", error);
    // 网络错误时使用本地默认值
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, "0");
    const day = String(now.getDate()).padStart(2, "0");
    billNo.value = `RECEIPT${year}${month}${day}001`;
    tempBillNo.value = billNo.value;
  }
};


// 结算明细数据
const settlementItems = ref([
  {
    account: "",
    amount: 0,
    method: "",
    settlementNo: "",
    remark: "",
  },
]);

// 合计金额
const totalAmount = ref(0);
// 表格行样式
const tableCellStyle = ({ row }) => {
  if (row.isTotalRow) {
    return { "background-color": "#fff3cd", "font-weight": "bold" };
  }
  return {};
};

// 判断是否是新增行
const isTotalRow = (index) => {
  return index === settlementItems.value.length - 1;
};

// 判断是否是可删除行
const isDeleteRow = (index) => {
  return (
    index < settlementItems.value.length - 1 && settlementItems.value.length > 1
  );
};

// 第一个表格的操作函数
const addSettlementRow = (index) => {
  settlementItems.value.splice(index, 0, {
    account: "",
    amount: 0,
    method: "",
    settlementNo: "",
    remark: "",
  });
  calculateTotal();
};

const removeSettlementRow = (index) => {
  settlementItems.value.splice(index, 1);
  calculateTotal();
};

// 第二个表格的操作函数
const addSourceDocRow = () => {
  SourceDocuments.value.push({
    docNo: "",
    businessType: "",
    docDate: "",
    slipPrice: 0,
    writtenOffAmount: 0,
    currentWriteOffAmount: 0,
    remark: "",
  });
};

const removeSourceDocRow = (index) => {
  SourceDocuments.value.splice(index, 1);
};
// 判断源单表格是否是最后一行（用于显示“+”）
const isSourceDocLastRow = (index) => {
  return index === SourceDocuments.value.length - 1;
};

// 判断源单表格是否可删除（非最后一行且总数 > 1）
const canDeleteSourceDocRow = (index) => {
  return SourceDocuments.value.length > 1 && index < SourceDocuments.value.length - 1;
};

// 计算合计金额
const calculateTotal = () => {
  totalAmount.value = settlementItems.value
    .filter((item) => !item.isTotalRow)
    .reduce((sum, item) => sum + (Number(item.amount) || 0), 0);

  // 更新合计行
  if (settlementItems.value[settlementItems.value.length - 1].isTotalRow) {
    settlementItems.value[settlementItems.value.length - 1].amount =
      totalAmount.value;
  }
};

// 初始化表格数据
const initTableData = () => {
  // 添加合计行
  settlementItems.value.push({
    account: "合计:",
    amount: 0,
    method: "",
    settlementNo: "",
    remark: "",
    isTotalRow: true,
  });
};

//源单数据
const SourceDocuments = ref([]);

// 模拟可选的源单数据（本地数据）
const availableSourceDocs = ref([]);
// 获取可用的源单数据（销售单据）
const getAvailableSourceDocs = async () => {
  if (!selectCustomer.value) {
    ElMessage.warning("请先选择客户");
    return;
  }

    console.log('已选择客户:', selectCustomer.value)
  try {
    const response = await axios.get('/finance/getSaleSlipByCustomerCode', {
      params: { customer_code: selectCustomer.value.code }
    });
    console.log('sale', response.data)
    if (response.data.code === 5200) {
      const saleslipData = response.data.saleSlipList.salesSlipList;
      let formattedDocs = [];
      
      if (Array.isArray(saleslipData)) {
        formattedDocs = saleslipData;
      } else if (saleslipData && typeof saleslipData === 'object') {
        formattedDocs = [saleslipData];
      } else {
        formattedDocs = [];
      }

      // 使用最新的已核销金额数据
      availableSourceDocs.value = formattedDocs.map(doc => ({
        docId: doc.id,
        docNo: doc.isReturn === 1 ? doc.returnCode : doc.code,
        businessType: doc.isReturn===1?'销售退货':'普通销售',
        docDate: doc.date,
        docAmount: doc.slipPrice || 0,
        sa: doc.slipPrice ||0,
        slipPrice: doc.isReturn===1?-(doc.slipPrice).toFixed(2):(doc.slipPrice).toFixed(2),
        thisPayment :doc.thisPayment || 0,
        writtenOffAmount: doc.isReturn===1? -(doc.written_off_amount).toFixed(2) :(doc.written_off_amount).toFixed(2) || 0,
        // 计算未核销金额
        get unwrittenOffAmount() {
          const docAmount = Number(this.slipPrice) || 0;
          const writtenOff = Number(this.writtenOffAmount) || 0;
          return (docAmount - writtenOff).toFixed(2);
        },
        remark: doc.remarks || "",
        customer_code: doc.customer_code
      }));
      
      console.log('格式化后的源单数据:', availableSourceDocs.value);
      ElMessage.success("获取源单数据成功");
    } else {
      ElMessage.error("获取源单数据失败：" + response.data.msg);
      availableSourceDocs.value = [];
    }
  } catch (error) {
    console.error("获取源单数据出错：", error);
    ElMessage.error("网络错误，无法获取源单数据");
    availableSourceDocs.value = [];
  }
};
//计算是否核算金额超过未核销金额
const validateWriteOffAmount = (row) => {
  const unwritten = parseFloat(row.unwrittenOffAmount) || 0;
  let current = parseFloat(row.currentWriteOffAmount) || 0;

  console.log('验证核销金额:', {
    businessType: row.businessType,
    unwritten,
    current
  });

  if (row.businessType === '普通销售') {
    if (current <= 0) {
      ElMessage.warning("普通销售的核销金额必须大于0");
      row.currentWriteOffAmount = 0.01;
    } else if (current > unwritten) {
      ElMessage.warning(`本次核销金额不能超过未核销金额 ${unwritten.toFixed(2)}`);
      row.currentWriteOffAmount = Number(unwritten.toFixed(2));
    }
  } else if (row.businessType === '销售退货') {
    if (current >= 0) {
      ElMessage.warning("销售退货的核销金额必须为负数");
      row.currentWriteOffAmount = -0.01;
    } else if (current < unwritten) {
      // 对于负数，current < unwritten 表示 current 比 unwritten 更负
      ElMessage.warning(`本次核销金额不能小于未核销金额 ${unwritten.toFixed(2)}`);
      row.currentWriteOffAmount = Number(unwritten.toFixed(2));
    }
  }

  calculateTotal();
};
// 表格合计计算方法
const getSummaries = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "合计";
      return;
    }

    // 根据列的prop属性计算不同列的合计
    const field = column.property;
    if (
      [
        "slipPrice",
        "writtenOffAmount",
        "unwrittenOffAmount",
        "currentWriteOffAmount",
      ].includes(field)
    ) {
      const values = data.map((item) => Number(item[field]) || 0);
      sums[index] = values.reduce((prev, curr) => prev + curr, 0).toFixed(2);
    } else {
      sums[index] = ""; // 非金额列不显示合计
    }
  });

  return sums;
};

//计算自动核销
const autoWriteOff = () => {
  if (!selectCustomer.value) {
    ElMessage.warning("请先选择客户");
    return;
  }
  if (SourceDocuments.value.length === 0) {
    ElMessage.warning("请先选择源单");
    return;
  }

  const totalPayment = totalAmount.value;
  if (totalPayment <= 0) {
    ElMessage.warning("付款金额必须大于0");
    return;
  }

  // 按单据日期升序排序
  const sortedDocs = [...SourceDocuments.value].sort(
    (a, b) => new Date(a.docDate) - new Date(b.docDate)
  );

  // 依次核销
  let remainingAmount = totalPayment;
  for (const doc of sortedDocs) {
    if (remainingAmount <= 0) break;

    const maxCanWriteOff = Number(doc.unwrittenOffAmount);
    const actualWriteOff = Math.min(maxCanWriteOff, remainingAmount);

    doc.currentWriteOffAmount = Number(actualWriteOff.toFixed(2));
    remainingAmount -= actualWriteOff;
    
    // 更新已核销金额和未核销金额
    // doc.writtenOffAmount = (Number(doc.writtenOffAmount) || 0) + actualWriteOff;
    
  }

  ElMessage.success("自动核销完成");
  calculateTotal();
};

//付款备注
const note = ref("");

// 计算总核销金额
const totalWriteOff = computed(() => {
  return SourceDocuments.value.reduce(
    (sum, doc) => sum + (Number(doc.currentWriteOffAmount) || 0),
    0
  );
});


// 计算预付款金额（总付款 - 总核销）
const remainAmount = computed(() => {
  const diff = Number(totalAmount.value) - Number(totalWriteOff.value);
  return diff > 0 ? Number(diff.toFixed(2)) : 0;
});
// 页面加载时初始化表格
initTableData();

//控制状态图片
const showStatus = ref(false);
const statusImageUrl = ref("");
const statusAltText = ref("");

const imagePaths = {
  waiting: require("@/assets/waitingpass.png"),
  passed: require("@/assets/passed.png"),
};

const receipt =ref(null);
//保存
const save = () => {
  // 1. 验证是否选择客户
  if (!selectCustomer.value) {
    ElMessage.warning("请先选择客户");
    return;
  }

  // 2. 验证所有结算行
  for (const item of settlementItems.value) {
    if (item.isTotalRow) continue;
    
    // 验证结算账户
    if (!item.account) {
      ElMessage.warning("请选择结算账户");
      return;
    }
    
    // 验证付款金额
    if (!item.amount || item.amount <= 0.01) {
      ElMessage.warning("付款金额必须大于0.01");
      return;
    }
  }

  // 3. 构造收款单数据
  const receiptData = {
     ...(isEditMode.value && { receipt_id: receipt_id.value }),
    // receipt_id: receipt_id.value,
    receipt_code: billNo.value,
    customer_id: selectCustomer.value.id,
    amount: totalAmount.value,
    receipt_method: settlementItems.value[0]?.method || '', 
    receipt_date: date.value,
    status: 0, // 保存未审核
    account_id: settlementItems.value[0]?.account || '', // 结算账户ID
    company_code: 'GS0001', 
    // 传递多个结算账户
    accountList: settlementItems.value
      .filter(item => !item.isTotalRow && item.account) // 过滤掉合计行和空账户
      .map(item => ({
        account_code: item.account, // 账户编码
        account_name: accountList.value.find(acc => acc.value === item.account)?.label || '', // 账户名称
        amount: item.amount || 0 // 该账户的付款金额
      })),
    current_written_off_all_amount: totalWriteOff.value,
    written_off_amount: 0.00,
    salesSlipList: SourceDocuments.value
      .filter(doc => doc.docNo)
      .map(doc => ({
        id: doc.docId,
        code: doc.docNo, // 销售单据编号
        date: doc.docDate, // 单据日期
        remarks: doc.remark || '', // 备注
        customer_code: selectCustomer.value?.code || '', // 客户编号
        company_code: 'GS0001', // 公司编码
        slipPrice: doc.docAmount,
        current_written_off_amount: doc.currentWriteOffAmount || 0, // 本次核销金额
        written_off_amount: doc.writtenOffAmount || 0 , // 已核销金额
      }))
      
  };

  console.log('保存的收款单数据:', isEditMode.value,receiptData);
  const url=isEditMode.value?'/finance/updateReceiptOrder':'/finance/addReceiptOrder';
  // 保存
  axios.post(url,receiptData)
    .then(response => {
      if (response.data.code === 5200) {
        ElMessage.success(isEditMode.value?"收款单修改成功":"收款单保存成功");
      }else if(response.data.code===5500){
        console.log(isEditMode.value?"修改失败：":"保存失败：");
         const errorMsg = isEditMode.value ? "修改失败：" : "保存失败：";
        ElMessage.error(errorMsg + (response.data.msg || ""));
      }
    })
    .catch(error => {
      console.error(isEditMode.value?"修改收款单出错：":"保存收款单出错：", error);
      ElMessage.error("网络错误，失败");
    });
};

//提交
const putit = async () => {
  console.log('billNo',billNo.value)
  // try{
    const response = await axios.get('/finance/getReceiptByCode',{params:{receiptCode:billNo.value}});
    receipt.value = response.data.receipt;
    console.log('得到的收款单',receipt.value)
    if(response.data.code===5500){
      ElMessage.error('该单据未保存，无法提交');
      return;
    }
    if(receipt.value.status===1 || receipt.value.status===2){
      ElMessage.error('该单据已提交或已审核，无法提交!!!');
      return;
    }
    const res = await axios.get('/finance/updateStatus', {
      params: {status: 1,receiptCode: billNo.value}
    });
    if(res.data.code===5200){
      ElMessage.success('提交成功');
    }else{
      console.log('提交失败',res.data)
      ElMessage.error('提交失败');
    }
  // }catch(error){
  //   console.log('提交失败',error);
  //   ElMessage.error('网络错误，失败')
  // }
};

// 审核 - 显示通过图片
const handleAudit = async () => {
  try{
    const response = await axios.get('/finance/getReceiptByCode',{params:{receiptCode:billNo.value}});
    receipt.value = response.data.receipt;
    console.log('得到的收款单',receipt.value)
    if(response.data.code===5500){
      ElMessage.error('该单据未提交，无法审核');
      return;
    }
    if(receipt.value.status!==1){
      ElMessage.error('该单据未提交或已审核，无法审核!!!');
      return;
    }
    const res = await axios.get('/finance/updateStatus', {
      params: {status: 2,receiptCode: billNo.value}
    });
    if(res.data.code===5200){
      ElMessage.success('审核成功');
    }else{
      console.log('审核失败',res.data)
      ElMessage.error('审核失败');
    }
  }catch(error){
    console.log('审核失败',error);
    ElMessage.error('网络错误，失败')
  }

};

//驳回
const back = async () => {
  try{
    const response = await axios.get('/finance/getReceiptByCode',{params:{receiptCode:billNo.value}});
    receipt.value = response.data.receipt;
    console.log('得到的收款单',receipt.value)
    if(response.data.code===5500){
      ElMessage.error('该单据未提交，无法驳回');
      return;
    }
    if(receipt.value.status!==1){
      ElMessage.error('该单据不是已提交状态，无法驳回!!!');
      return;
    }
    const res = await axios.get('/finance/updateStatus', {
      params: {status: 3,receiptCode: billNo.value}
    });
    if(res.data.code===5200){
      ElMessage.success('驳回成功');
    }else{
      console.log('驳回失败',res.data)
      ElMessage.error('驳回失败');
    }
  }catch(error){
    console.log('驳回失败',error);
    ElMessage.error('网络错误，失败')
  }
  
};

// 重置表单
const resetForm = () => {
  customerForm.value = "";
  TotalDebt.value = "";
  selectCustomer.value = null;
  responsible.value = "";
  date.value = dayjs().format('YYYY-MM-DD');
  note.value = "";
  isEditMode.value=false;
  
  // 重置结算明细
  settlementItems.value = [
    {
      account: "",
      amount: 0,
      method: "",
      settlementNo: "",
      remark: "",
    },
    {
      account: "合计:",
      amount: 0,
      method: "",
      settlementNo: "",
      remark: "",
      isTotalRow: true,
    }
  ];
  
  // 重置源单数据
  SourceDocuments.value = [];
  // 重新生成单据编号
  generateDefaultBillNo();
};
// 防止输入超过最大值和非法字符
const preventExceedMax = (event, maxAmount, row) => {
  const key = event.key;
  
  // 阻止输入字母e等非法字符
  if (key === 'e' || key === 'E') {
    event.preventDefault();
    return;
  }

  // 如果是销售退货单，允许输入负号
  if (row.businessType === '销售退货' && key === '-') {
    // 允许输入负号，不做阻止
    return;
  }

  // 普通销售单禁止输入负号
  if (row.businessType === '普通销售' && key === '-') {
    event.preventDefault();
    ElMessage.warning("普通销售的核销金额不能为负数");
    return;
  }

  // 获取当前输入的值
  const currentValue = event.target.value;
  const newValue = currentValue + event.key;
  
  // 如果是销售退货单，特殊处理负数比较
  if (row.businessType === '销售退货') {
    const newValueNum = Number(-newValue);
    const maxAmountNum = Number(-maxAmount);
    
    // 对于负数，newValue > maxAmount 表示 newValue 比 maxAmount 更接近0
    if (!isNaN(newValueNum) && !isNaN(maxAmountNum) && newValueNum > maxAmountNum) {
      event.preventDefault();
      ElMessage.warning(`输入金额不能大于${maxAmountNum.toFixed(2)}`);
    }
  } else {
    // 普通销售单的正常验证
    if (maxAmount && Number(newValue) > Number(maxAmount)) {
      event.preventDefault();
      ElMessage.warning(`输入金额不能超过${maxAmount}`);
    }
  }
};

// 结算账户列表
const accountList = ref([]);
// 页面加载时获取结算账户列表
const getAccountList = async () => {
  try {
    const response = await axios.get("/finance/allAccount",{params:{company_code:'GS0001'}});
    if (response.data.code === 5200) {
      accountList.value = response.data.allAccount.map(account => ({
        label: account.account_name, 
        value: account.account_code 
      }));
    } else {
      ElMessage.error("获取结算账户失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取结算账户出错：", error);
    ElMessage.error("网络错误，无法获取结算账户数据");
  }
};
//新增
const addNew = () => {
  // 如果当前在编辑模式（URL 有 code），则跳转到无参路径，触发新增
  if (route.query.code) {
    router.push({ 
      path: '/finance/receipt-slip',
      query: {} 
    });
  } else {
    resetForm();
  }
};

</script>

<style>
.bills {
  position: relative;
  background: #ffffff;
  border: 1px solid #cfcfcf;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  padding: 20px 20px 10px 20px; /* 顶部内边距还原为 20px */
  /* height: 100%; */
}
.label_input {
  margin-right: 10px;
}
.searchDiv {
  display: inline-block;
  margin-right: 15px;
}
.el-table .selected-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
  background-color: var(--el-table-tr-bg-color);
}
.bill-no {
  cursor: pointer;
  padding: 0 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.bill-no:hover {
  background-color: #f5f5f5;
  text-decoration: underline;
}

.settlement-table {
  margin-top: 20px;
}

.el-table .cell {
  padding: 8px 12px;
}

/* 标记必填项 */
.el-table .el-table__header .cell .required {
  color: #f56c6c;
  margin-right: 2px;
}

.middle-div {
  float: right;
  margin-top: 5px;
  margin-bottom: 5px;
}

.el-table__footer .el-table__cell {
  background-color: #fff3cd !important; /* 橙色背景 */
  font-weight: bold !important;
}

.note {
  margin-top: 7px;
}

/* 固定在右下角的样式 */
.status-indicator {
  position: absolute; /* 固定定位，不随滚动条移动 */
  right: 50px; /* 距离右边50px */
  bottom: 100px; /* 距离底部100px */
  z-index: 9999; /* 确保显示在最上层 */
  border-radius: 4px; /* 圆角边框 */
  overflow: hidden; /* 内容超出部分隐藏 */
}

/* 图片样式 */
.status-image {
  width: 120px; /* 根据实际图片大小调整 */
  height: 120px; /* 保持宽高比 */
  display: block;
}

  .el-table__body tr:hover > td,
   .el-table__body tr.el-table__row:hover > td,
   .el-table--enable-row-hover .el-table__body tr:hover > td {
     background-color: #fff4bf !important;
   }
</style>